﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XTYAPI.通讯.WebAPI
{
    public class WebAPIServer
    {
        private HttpListener httpListener;
        private bool isListening = false;
        /// <summary>
        /// WebApiServer启动
        /// </summary>
        /// <returns></returns>
        public bool WebAPIServerStart(string url = "http://+:805/")
        {
            if (!HttpListener.IsSupported)
            {
                //此端口不能打开
                return false;
            }

            httpListener = new HttpListener();
            httpListener.Prefixes.Add(url); // 注意替换为你想要的端口号

            httpListener.Start();
            isListening = true;

            ReceiveRequest();
            return true;
        }
        /// <summary>
        /// 继续监听下一个请求
        /// </summary>
        private void ReceiveRequest()
        {
            httpListener.BeginGetContext(new AsyncCallback(EndReceiveRequest), null);
        }
        /// <summary>
        /// 回调函数调用
        /// </summary>
        /// <param name="ar"></param>
        private void EndReceiveRequest(IAsyncResult ar)
        {
            if (isListening)
            {
                #region 得到Http请求
                HttpListenerContext context = httpListener.EndGetContext(ar);
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                string result = string.Empty;
                #endregion
                if (request.HttpMethod == "GET")
                {
                    #region GET路由处理
                    if (request.RawUrl.StartsWith("/api/op="))
                    {
                        string str = request.RawUrl.Replace("/api/op=", "");
                        string[] values = str.Split('?');
                        string method = string.Empty;
                        if (values.Length > 0)
                        {
                            method = values[0];
                        }
                        if (method == "test")
                        {
                            string json = string.Empty;
                            using (StreamReader resader = new StreamReader(request.InputStream, Encoding.UTF8))
                            {
                                json = resader.ReadToEnd();
                            }
                            result = Test(json);
                        }
                    }
                    #endregion
                }
                if (request.HttpMethod == "POST")//一般用POST多一些，因为post是加密处理
                {

                }
                #region 数据返回
                string responseString = $"HTTP /{request.ProtocolVersion}{(int)HttpStatusCode.OK}{HttpStatusCode.OK.ToString()}{result}";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);

                response.StatusCode = (int)HttpStatusCode.OK;
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();

                ReceiveRequest(); // 继续监听下一个请求
                #endregion
            }
        }
        /// <summary>
        /// 给客户端回复消息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private string Test(string json)
        {
            return "靓仔你好";
        }
    }
}
